<template>
  <el-card class="report-container">
    <div class="report-header">
      <div class="header-date-comp">
        <el-radio-group style="margin-right: 30px;padding: 5px" v-model="dateType" @change="dateChange">
          <el-radio label="day">按日</el-radio>
          <el-radio label="month">按月</el-radio>
          <el-radio label="year">按年</el-radio>
        </el-radio-group>
        <el-date-picker
          v-if="dateType==='day'"
          v-model="time"
          type="date"
          :clearable="false"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"></el-date-picker>
        <el-date-picker
          v-if="dateType==='month'"
          v-model="time"
          type="month"
          :clearable="false"
          placeholder="选择月份"
          value-format="yyyy-MM"></el-date-picker>
        <el-date-picker
          v-if="dateType==='year'"
          v-model="time"
          type="year"
          :clearable="false"
          placeholder="选择年"
          value-format="yyyy"></el-date-picker>
        <el-button style="margin: 10px" type="primary"  @click.native="timeSearch(false)">筛选</el-button>
      </div>
      <div>
        <el-tooltip content="添加到快捷搜索栏">
          <el-button size="mini"  circle @click.native="timeSearch(true)">
            <i class="el-icon-plus" />
          </el-button>
        </el-tooltip>
        <el-tooltip content="导出excel">
          <el-button size="mini"  circle @click.native="remoteExport">
            <svg-icon icon-class="f-export" class-name="im-ex-icon" />
          </el-button>
        </el-tooltip>
      </div>
    </div>
    <el-tabs v-model="rpTab">
      <el-tab-pane label="汇总" name="total">
        <div style="width: 100%;margin-top: 30px;margin-bottom: 30px;text-align: center">
          <h3>**{{title}}</h3>
        </div>
        <el-tabs v-model="searchTabsValue" type="card" closable @tab-remove="removeTab" @tab-click="clickTimeTab">
          <el-tab-pane
            v-for="(item, index) in searchTabs"
            :key="item.name"
            :label="item.title"
            :name="item.name"></el-tab-pane>
        </el-tabs>
        <el-tag type="info">{{subTitle}}</el-tag>
        <el-table :data="reportData"
                  style="width: 100%"
                  border
                  v-loading="tableLoading"
                  element-loading-text="报表生成中..."
                  element-loading-spinner="el-icon-loading">
          <el-table-column v-for="(col,idx) in reportCols" :key="idx" :prop="col.prop" :label="col.label" :type="col.type" :width="col.width" :fixed="col.fixed">
            <el-table-column v-for="(child, index) in col.children" :key="index" :prop="child.prop" :label="child.label" ></el-table-column>
          </el-table-column>
        </el-table>
        <el-alert title="备注:  所有实时值,按日均值填写" type="info" show-icon></el-alert>
      </el-tab-pane>
      <el-tab-pane label="明细" name="detail" v-loading="detailLoading" :disabled="detailPanelDisable">
        <template v-if="dateType!=='day'">
          <el-skeleton :rows="12" animated v-if="!detailData.length" />
          <el-row v-for="(item,index) in detailData" :key="index">
            <rp-detail-cell :cell-data="item" />
          </el-row>
        </template>
        <template v-else>
          <el-empty description="日数据无明细" />
        </template>
      </el-tab-pane>
    </el-tabs>

  </el-card>

</template>

<script>
  import analysisApi from "@/api/analysis"
  import {formMonths} from "@/utils/constants"
  import {parseTime} from "@/utils"
  import rpDetailCell from "../rpDetailCell"

  const today = parseTime(new Date(),'{y}-{m}-{d}')
  export default {
    name: "formPanel",
    props:{
      query:{
        type:Object,
        required:true
      }
    },
    components:{
      'rpDetailCell':rpDetailCell
    },
    data(){
      return {
        title:'电厂锅炉、汽机技术指标统计表',
        subTitle:'三、锅炉技术指标',
        dateType:'day',
        today,
        formMonths,
        tableLoading:false,
        downloadLoading: false,
        detailLoading:false,
        content:'暂无报表数据!',
        reportCols:[],
        reportData: [],
        time:today,
        searchTabsValue:'',
        searchTabsLabel:'',
        searchTabs:[],
        tabIndex:0,
        detailPanelDisable:true,
        detailData:[],
        rpTab:'total'
      }
    },
    computed:{
      excelFileName(){
        return this.title+this.time
      }
    },
    methods:{
      fetchData(save=false){
        if (!this.query.orgnization_id){
          this.$message.warning("请选择组织!")
          this.reportCols=null
          this.reportData=null
          return
        }
        let rqParams = Object.assign({},this.query)
        rqParams.time=this.time
        const dateComps = this.time.split('-')
        if (this.dateType==='month'){
          if (dateComps.length>2)
            rqParams.time=`${dateComps[0]}-${dateComps[1]}`
        }else if (this.dateType==='year'){
          if (dateComps.length>2)
            rqParams.time=dateComps[0]
        }
        this.tableLoading=true
        this.detailLoading=true
        analysisApi.singleReportDetail(rqParams).then(res=>{
          const dateList = Object.keys(res.data)
          let dtArr = []
          dateList.forEach(date=>{
            const tb = this.convertData(res.data[date])
            const cols = [tb[0]]
            const datas = [tb[1]]
            dtArr.push({
              date:date,
              reportCols:cols,
              reportData:datas
            })
          })
          this.detailData = dtArr
          this.detailLoading=false
        })
        analysisApi.singleReport(rqParams).then(res=>{
          const tableData = this.convertData(res.data)
          this.reportCols = tableData[0]
          setTimeout(()=>{
            this.reportData = tableData[1]
            if (save)
              this.addTab(rqParams.time)
            this.tableLoading=false
          },200)
        })
      },
      timeSearch(withQuick=false){
        if (!withQuick){
          this.searchTabsValue=''
          this.searchTabsLabel=''
          this.fetchData()
          return
        }
        this.$confirm('确定添加到快捷搜索栏吗?', '提示', confirm).then(() => {
          this.fetchData(true)
        }).catch(() => {
          this.searchTabsValue=''
          this.searchTabsLabel=''
          this.fetchData()
        })
      },
      dateChange(val){
        this.detailPanelDisable=false
        if (val=='day')
          this.detailPanelDisable=true
        this.time=this.today
        this.detailData=[]
        this.timeSearch(false)
      },
      convertData(dataList){
        let tbCols=[]
        let tbArr=[]
        const allDevs = Object.keys(dataList)
        for (let idx in dataList){
          const data = dataList[idx]
          if (idx==allDevs[0]){
            tbCols.push({
              prop:'name',
              label:'锅炉号',
              children:[],
              fixed:true
            })
            for (let tag of data){
              tbCols.push({
                prop:null,
                label:tag.alias,
                fixed:false,
                children:[{
                  prop:tag.alias,
                  label:tag.messure
                }]
              })
            }
          }
          let tbEntity = {name:idx}
          for (let cidx in data){
            const cell = data[cidx]
            if (cell)
              tbEntity[cell.alias] = cell.value
            else{
              const name_key = tbCols[parseInt(cidx)+1].prop
              tbEntity[name_key] = ""
            }

          }
          tbArr.push(tbEntity)
        }
        return [tbCols,tbArr]
      },
      localExport(){
        import('@/vendor/Export2Excel').then(excel => {
          let multiHeader = []
          let header = []
          for (let col of this.reportCols){
            if (col.type=='index')
              continue
            header.push(col.label)
          }
          const list = this.reportData
          const data = list.map(v => Object.values(v))
          const merges = []
          const exportJson={
            filename:this.excelFileName,
            multiHeader,
            header,
            merges,
            data
          }
          excel.export_json_to_excel(exportJson)
          this.$message.success("导出excel成功")
        })
      },
      async remoteExport(){
        const downLoading = this.$loading({
          lock: true,
          text: '导出中...',
          spinner: 'el-icon-loading',
        });
        const token = await this.$store.dispatch('user/refreshToken')
        const baseHost = 'http://analysisapi.wm-mis.com/api'
        let dtm=this.time
        const dateComps = this.time.split('-')
        if (this.dateType==='month'){
          if (dateComps.length>2)
            dtm=`${dateComps[0]}-${dateComps[1]}`
        }else if (this.dateType==='year'){
          if (dateComps.length>2)
            dtm=dateComps[0]
        }
        const durl = `${baseHost}/data-analysis/single-download?token=${token}&orgnization_id=${this.query.orgnization_id}&module_name=${this.query.module_name}&time=${dtm}`
        window.open((durl),"_self")
        setTimeout(()=>{
          downLoading.close()
        },1500)
      },
      clickTimeTab(tab){
        const tab_time = tab.$options.propsData.label
        const dateCompsLen = tab_time.split('-').length
        this.dateType = dateCompsLen>2?'day':dateCompsLen<2?'year':'month'
        this.time = tab_time
        this.fetchData()
      },
      addTab(title) {
        let newTabName = ++this.tabIndex + '';
        this.searchTabs.push({
          title: title,
          name: newTabName
        });
        this.searchTabsValue = newTabName
        this.searchTabsLabel = title
      },
      removeTab(targetName) {
        let tabs = this.searchTabs;
        let activeName = this.searchTabsValue
        let activeLabel = this.searchTabsLabel
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name
                activeLabel = nextTab.title
              }
            }
          });
        }
        this.searchTabsValue = activeName
        this.searchTabsLabel = activeLabel
        this.searchTabs = tabs.filter(tab => tab.name !== targetName);
        this.clickTimeTab({$options:{propsData:{label:activeLabel}}})
      }

    }

  }
</script>

<style scoped lang="scss">
  .report-container{
    padding: 5px;
    .report-header{
      width: 100%;
      padding: 10px;
      display: flex;
      flex-direction: row;
      justify-content:space-between;
      align-items: center;
      margin-bottom: 20px;

    }

  }
</style>
